"""
客户跟进表单类
"""
from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, SelectField, DateTimeField, BooleanField, SubmitField, SelectMultipleField
from wtforms.validators import DataRequired, Length, Optional
from wtforms.widgets import TextArea, CheckboxInput, ListWidget
from app.models.user import User
from app.models.customer import Customer, Contact
from app.models.project import Project


class MultiCheckboxField(SelectMultipleField):
    """
    自定义多选字段，使用复选框显示
    """
    widget = ListWidget(prefix_label=False)
    option_widget = CheckboxInput()


class FollowUpForm(FlaskForm):
    """客户跟进表单"""
    
    # 基本信息
    customer_id = SelectField('选择客户', coerce=int, validators=[DataRequired(message='请选择客户')])
    contact_ids = MultiCheckboxField('相关联系人', coerce=int)
    project_id = SelectField('关联项目', coerce=int, validators=[Optional()])
    
    # 跟进信息
    followup_time = DateTimeField('跟进时间', format='%Y-%m-%d %H:%M', validators=[DataRequired(message='请选择跟进时间')])
    method = SelectField('跟进方式', choices=[
        ('电话', '电话'),
        ('邮件', '邮件'),
        ('会面', '会面'),
        ('拜访', '拜访'),
        ('微信', '微信'),
        ('其他', '其他')
    ], validators=[DataRequired(message='请选择跟进方式')])
    content = TextAreaField('跟进内容', validators=[DataRequired(message='请输入跟进内容'), Length(min=5, message='跟进内容至少5个字符')])
    result = TextAreaField('跟进结果')
    next_followup_time = DateTimeField('下次跟进时间', format='%Y-%m-%d %H:%M', validators=[Optional()])
    
    # 解决方案配合
    solution_support = BooleanField('需要解决方案人员配合')
    solution_support_user_id = SelectField('配合人员', coerce=int)
    solution_support_time = DateTimeField('配合时间', format='%Y-%m-%d %H:%M', validators=[Optional()])
    
    # 提交按钮
    submit = SubmitField('保存跟进记录')
    
    def __init__(self, *args, **kwargs):
        from flask_login import current_user
        
        super(FollowUpForm, self).__init__(*args, **kwargs)
        
        # 根据用户角色动态设置客户选项
        if current_user.role == 'sales':
            # 销售人员只能看到自己负责的客户
            self.customer_id.choices = [(c.id, f"{c.name} ({c.customer_number})") 
                                      for c in Customer.query.filter_by(manager_id=current_user.id).all()]
        else:
            # 管理员和其他角色可以看到所有客户
            self.customer_id.choices = [(c.id, f"{c.name} ({c.customer_number})") for c in Customer.query.all()]
        
        # 初始化联系人选项为空，将在选择客户后通过AJAX加载
        self.contact_ids.choices = []
        # 动态设置解决方案人员选项（这里假设解决方案人员是特定角色的用户）
        solution_users = User.query.filter_by(role='solution').all()
        if solution_users:
            self.solution_support_user_id.choices = [(0, '请选择配合人员')] + [(u.id, u.username) for u in solution_users]
        else:
            # 如果没有解决方案用户，则使用开发人员作为备选
            dev_users = User.query.filter_by(role='developer').all()
            if dev_users:
                self.solution_support_user_id.choices = [(0, '请选择配合人员')] + [(u.id, f"{u.username} (开发人员)") for u in dev_users]
            else:
                # 如果没有开发人员，则使用所有管理员和项目经理
                admin_users = User.query.filter(User.role.in_(['admin', 'project_manager'])).all()
                if admin_users:
                    self.solution_support_user_id.choices = [(0, '请选择配合人员')] + [(u.id, f"{u.username} ({u.role})") for u in admin_users]
                else:
                    # 如果没有任何符合条件的用户，则只提供默认选项
                    self.solution_support_user_id.choices = [(0, '暂无可选配合人员')]
        # 初始化项目选项为空，将在选择客户后通过AJAX加载
        self.project_id.choices = [(0, '请先选择客户')]
    
    def validate_contact_ids(self, field):
        """验证联系人是否属于所选客户"""
        if field.data:
            customer = Customer.query.get(self.customer_id.data)
            if customer:
                contact_ids = [c.id for c in customer.contacts]
                for contact_id in field.data:
                    if contact_id not in contact_ids:
                        raise ValueError('所选联系人不属于该客户')


class FollowUpFilterForm(FlaskForm):
    """客户跟进筛选表单"""
    
    # 筛选条件
    customer_id = SelectField('客户', coerce=int)
    project_id = SelectField('项目', coerce=int)
    manager_id = SelectField('跟进人', coerce=int)
    method = SelectField('跟进方式', choices=[
        ('', '全部'),
        ('电话', '电话'),
        ('邮件', '邮件'),
        ('会面', '会面'),
        ('拜访', '拜访'),
        ('微信', '微信'),
        ('其他', '其他')
    ])
    solution_support = SelectField('解决方案配合', choices=[
        ('', '全部'),
        ('yes', '需要配合'),
        ('no', '不需要配合'),
        ('confirmed', '已确认'),
        ('pending', '待确认')
    ])
    start_date = DateTimeField('开始日期', format='%Y-%m-%d', validators=[Optional()])
    end_date = DateTimeField('结束日期', format='%Y-%m-%d', validators=[Optional()])
    
    # 提交按钮
    submit = SubmitField('筛选')
    
    def __init__(self, *args, **kwargs):
        super(FollowUpFilterForm, self).__init__(*args, **kwargs)
        # 动态设置客户选项
        self.customer_id.choices = [(0, '全部客户')] + [(c.id, c.name) for c in Customer.query.all()]
        # 动态设置项目选项
        self.project_id.choices = [(0, '全部项目')] + [(p.id, p.name) for p in Project.query.all()]
        # 动态设置跟进人选项
        self.manager_id.choices = [(0, '全部跟进人')] + [(u.id, u.username) for u in User.query.all()]


class SolutionSupportConfirmForm(FlaskForm):
    """解决方案配合确认表单"""
    
    confirmed = BooleanField('确认配合')
    notes = TextAreaField('备注')
    submit = SubmitField('确认')